/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;
//<editor-fold defaultstate="collapsed" desc="Import">
import hibernate.model.dao.ChiTietDonDatHangDAO;
import hibernate.model.dao.CodeSanPhamDAO;
import hibernate.model.dao.DonDatHangDAO;
import hibernate.model.dao.KhachHangDAO;
import hibernate.model.dao.LoaiThanhToanDAO;
import hibernate.model.dao.SanPhamDAO;
import hibernate.model.dao.ThanhToanTanNoiDAO;
import hibernate.model.dao.ThanhToanTangDAO;
import hibernate.model.dao.ThanhToanTrucTuyenDAO;
import hibernate.pojo.Chitietdondathang;
import hibernate.pojo.Codesanpham;
import hibernate.pojo.Dondathang;
import hibernate.pojo.Khachhang;
import hibernate.pojo.Loaithanhtoan;
import hibernate.pojo.Sanpham;
import hibernate.pojo.Thanhtoantang;
import hibernate.pojo.Thanhtoantannoi;
import hibernate.pojo.Thanhtoantructuyen;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


//</editor-fold>

/**
 *
 * @author phathuynh
 */
@WebServlet(name="cartcontroller", urlPatterns={"/cartcontroller"})
public class cartcontroller extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, ParseException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try
        {
            request.setCharacterEncoding("UTF-8");
            HttpSession session = request.getSession();
            String action = request.getParameter("action");
            String masp = request.getParameter("maSanPham");
            int maSanPham = Integer.parseInt(masp);
            Sanpham sanphamban = SanPhamDAO.getProductByID(maSanPham);
            request.setAttribute("SanPhamDatMua", sanphamban);
            if(action != null)
            {
                //<editor-fold defaultstate="collapsed" desc="Click vào nút Mua hàng -> xem cart">
                if(action.equals("buy"))
                {
                    if(masp!=null)
                    {
                        request.getRequestDispatcher("pagestile/cart.jsp").forward(request, response);
                    }        
                }
                //</editor-fold>
                
                //<editor-fold defaultstate="collapsed" desc="Click vào link Mua tặng bạn bè -> view page">
                else if(action.equals("present"))
                {
                    request.getRequestDispatcher("pagestile/present.jsp").forward(request, response);
                }
                //</editor-fold>
                
                //<editor-fold defaultstate="collapsed" desc="Click vào nút Hoàn Tất Đơn Đặt Hàng">
                else if(action.equals("order")) // click vào nút đơn đặt hàng
                {
                    //Suppose available
                    Dondathang ddh = new Dondathang();
                    DonDatHangDAO ddhDAO = new DonDatHangDAO();
                    Chitietdondathang ctddh = new Chitietdondathang();
                    ChiTietDonDatHangDAO ctddhDAO = new ChiTietDonDatHangDAO();
                    int soLuongDat = Integer.parseInt(request.getParameter("quantity"));
                    double triGiaDonHang = sanphamban.getGiaBan()*soLuongDat;
                    int maLoaiThanhToan = Integer.parseInt(request.getParameter("paytype"));
                    Khachhang khachhang = (Khachhang) session.getAttribute("KhachHang");
                    if(khachhang == null)
                    {
                        request.getRequestDispatcher("pagestile/login.jsp").forward(request, response);
                    }
                    
                    if(maLoaiThanhToan==1||maLoaiThanhToan==3){
                        if(khachhang.getSoDuTaiKhoan() < triGiaDonHang)
                        {
                            response.sendRedirect("cannotaffordcontroller?action=unaffordable");
                            return;
                        }
                        double tienSauKhiMuaHang = khachhang.getSoDuTaiKhoan() - triGiaDonHang;
                        khachhang.setSoDuTaiKhoan(tienSauKhiMuaHang);
                        KhachHangDAO.updateCustomerInfo(khachhang);
                    }
                    Loaithanhtoan loaiThanhToan = LoaiThanhToanDAO.layLoaiThanhToan(maLoaiThanhToan);
                    Date ngayDat = DonDatHangDAO.LayNgayHeThong();
                    maSanPham = Integer.parseInt(masp);
                    
                    int trangThaiXacNhan = 0;
                    int trangThaiGiaoHang = 0;
                    int tinhTrang = 0;
                    String ghiChu = "Online paid";
                    
                    //Set order
                    ddh.setKhachhang(khachhang);
                    ddh.setLoaithanhtoan(loaiThanhToan);
                    ddh.setNgayDat(ngayDat);
                    ddh.setTriGiaDonHang(triGiaDonHang);
                    ddh.setTrangThaiXacNhan(trangThaiXacNhan);
                    ddh.setTrangThaiGiaoHang(trangThaiGiaoHang);
                    ddh.setTinhTrang(tinhTrang);
                    ddh.setGhiChu(ghiChu);
                    //Insert into Order
                    boolean addingOrderResult = ddhDAO.themDonDatHang(ddh); 
                    if(addingOrderResult==false){
                        out.print("System error - Adding order fail");
                    }

                    //<editor-fold defaultstate="collapsed" desc="2. Create Order detail">
                    int maDonDatHangCuoiCung = ChiTietDonDatHangDAO.getLastOrderID();
                    Dondathang donDatHang = ChiTietDonDatHangDAO.getLastOrder(maDonDatHangCuoiCung);
                    soLuongDat = Integer.parseInt(request.getParameter("quantity"));
                    maSanPham = Integer.parseInt(request.getParameter("maSanPham"));
                    //sanPham = SanPhamDAO.getProductByID(maSanPham);
                    double donGiaBan = sanphamban.getGiaBan();
                    double thanhTien = donGiaBan*soLuongDat;
                    //set order detail
                    ctddh.setDondathang(donDatHang);
                    ctddh.setSanpham(sanphamban);
                    ctddh.setSoLuongDat(soLuongDat);
                    ctddh.setDonGiaBan(donGiaBan);
                    ctddh.setThanhTien(thanhTien);
                    int addingOrderDetailResult = ctddhDAO.addOrderDetail(ctddh);//nho doi boolean -> int
                    if(addingOrderDetailResult  != 1){
                        out.print("System error - Try again later");
                    }
                    //</editor-fold>
                    
                    //<editor-fold defaultstate="collapsed" desc="3. Create Product Code">
                    Codesanpham codeSanPham = new Codesanpham();
                    for(int i=0;i<soLuongDat;i++)
                    {
                        int maxcode = CodeSanPhamDAO.getLastOrderID();
                        String max = String.valueOf(maxcode);
                        String codeMD5 = CodeSanPhamDAO.MD5(max);
                        codeSanPham.setChitietdondathang(ctddh);
                        codeSanPham.setCodeSanPham(codeMD5);
                        codeSanPham.setTinhTrang(tinhTrang);
                        codeSanPham.setGhiChu(ghiChu);
                        int res = CodeSanPhamDAO.addProductCode(codeSanPham);
                        if(res!=1){
                            out.print("System error - Try again later");
                        }
                        continue;
                    }
                    //</editor-fold>
       
                    //<editor-fold defaultstate="collapsed" desc="4. Create order type">
                    if(maLoaiThanhToan == 1)
                    {   //ONLINE
                        Thanhtoantructuyen tttt = new Thanhtoantructuyen();
                        //adding dondathang
                        tttt.setDondathang(donDatHang);
                        ThanhToanTrucTuyenDAO.themThanhToanOnline(tttt);
                        request.getRequestDispatcher("pagestile/completeorder.jsp").forward(request, response);
                    }
                    else if(maLoaiThanhToan == 2)
                    {   //DELIVERY
                        Thanhtoantannoi tttn = new Thanhtoantannoi();
                        String tenNguoiNhan = request.getParameter("tenNguoiNhan");
                        String soDienThoai = request.getParameter("soDienThoai");
                        String thanhPho = request.getParameter("thanhPho");
                        String quan = request.getParameter("quan");
                        String phuong = request.getParameter("phuong");
                        String soNha = request.getParameter("soNha");
                        String tenDuong = request.getParameter("tenDuong");
                        String ngayNhanHang = request.getParameter("ngayNhanHang");
                        
                        String gioNhanHangTu = request.getParameter("gioNhanHangTu");
                        gioNhanHangTu = gioNhanHangTu+":00";
                        SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm:ss");    // Định dạng giờ cho giờ nhận hàng
                        Date dgioNhanHangTu = null;
                        if(!gioNhanHangTu.equals(""))
                        {
                            dgioNhanHangTu = sdfTime.parse(gioNhanHangTu);
                        }
                        Date dgioNhanHangDen = null;
                        String gioNhanHangDen = request.getParameter("gioNhanHangDen");
                        gioNhanHangDen = gioNhanHangDen+":00";
                        if(!gioNhanHangDen.equals(""))
                        {
                            dgioNhanHangDen = sdfTime.parse(gioNhanHangDen);
                        }
                        Date ngaynh = null;
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
                        if(!ngayNhanHang.equals("")){
                            ngaynh = sdf.parse(ngayNhanHang);    
                        }
                        
                        String loiNhan = request.getParameter("loiNhan");
                        int tinhTrangtt  = 1;
                        String ghiChutt = "will be paid at home";
                        
                        //set tttn
                        tttn.setDondathang(donDatHang);
                        tttn.setTenNguoiNhan(tenNguoiNhan);
                        tttn.setSoDienThoai(soDienThoai);
                        tttn.setThanhPho(thanhPho);
                        tttn.setQuan(quan);
                        tttn.setPhuong(phuong);
                        tttn.setSoNha(soNha);
                        tttn.setTenDuong(tenDuong);
                        tttn.setNgayNhanHang(ngaynh);
                        tttn.setGioNhanHangTu(dgioNhanHangTu);
                        tttn.setGioNhanHangDen(dgioNhanHangDen);
                        tttn.setLoiNhan(loiNhan);
                        tttn.setTinhTrang(tinhTrangtt);
                        tttn.setGhiChu(ghiChutt);
                        boolean res = ThanhToanTanNoiDAO.addHomeDelivery(tttn);
                        if(res==true){
                            request.getRequestDispatcher("pagestile/completeorder.jsp").forward(request, response);    
                        }
                    }
                    else if(maLoaiThanhToan == 3)
                    {   //PRESENT
                        Thanhtoantang thanhToanTang = new Thanhtoantang();
                        String tenNguoiGui = request.getParameter("tenNguoiGui");
                        int soLuongGui = Integer.parseInt(request.getParameter("quantity"));
                        String tenNguoiNhan = request.getParameter("tenNguoiNhan");
                        String emailNguoiNhan = request.getParameter("emailNguoiNhan");
                        String soDienThoaiNguoiNhan = request.getParameter("soDienThoaiNguoiNhan");
                        String loiNhan = request.getParameter("loiNhan");
                        int tinhTrangqt = 1;
                        String ghiChuqt = "Thanh toán tận nhà nhé!";
                        //set attribute
                        thanhToanTang.setDondathang(donDatHang);
                        thanhToanTang.setTenNguoiGui(tenNguoiGui);
                        thanhToanTang.setSoLuongGui(soLuongGui);
                        thanhToanTang.setTenNguoiNhan(tenNguoiNhan);
                        thanhToanTang.setEmailNguoiNhan(emailNguoiNhan);
                        thanhToanTang.setSoDienThoaiNguoiNhan(soDienThoaiNguoiNhan);
                        thanhToanTang.setLoiNhan(loiNhan);
                        thanhToanTang.setTinhTrang(tinhTrangqt);
                        thanhToanTang.setGhiChu(ghiChuqt);
                        boolean pre = ThanhToanTangDAO.addPresentOrder(thanhToanTang);
                        if(pre==false){
                            out.print("Adding present order error");
                        }
                        request.getRequestDispatcher("pagestile/completeorder.jsp").forward(request, response);
                    }
                }
                //</editor-fold>
                
                //<editor-fold defaultstate="collapsed" desc="Hoàn tất đơn đặt hàng, cần chuyển link.">
                else if(action.equals("completeorder"))
                {
                    response.sendRedirect("cartcontroller?");
                }
                //</editor-fold>
                
                //</editor-fold>
                
                //<editor-fold defaultstate="collapsed" desc="Click vào link thanh toán online">
                if(action.equals("payonline"))
                {
                    //String masp = request.getParameter("maSanPham");
                    if(masp!=null)
                    {
                        request.setAttribute("SanPhamDatMua", sanphamban);
                        request.getRequestDispatcher("pagestile/cart.jsp").forward(request, response);
                    }
                }
                //</editor-fold>
                
                //<editor-fold defaultstate="collapsed" desc="Click vào link giao hàng tận nơi">
                else if(action.equals("delivery"))
                {
                    if(masp!=null)
                    {
                        request.setAttribute("SanPhamDatMua", sanphamban);
                        request.getRequestDispatcher("pagestile/delivery.jsp").forward(request, response);
                    }
                }
                //</editor-fold>
            }
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(cartcontroller.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(cartcontroller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
 